<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-select v-model="queryParams.month" placeholder="请选择" clearable>
          <el-option
            v-for="dict in monthList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="周数" prop="week">
        <el-select v-model="queryParams.week" placeholder="请选择" clearable>
          <el-option
            v-for="dict in weekList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="teamSelect"
          @click="printPlan"
          v-hasPermi="['factory:factorywplan:edit']"
        >打印周计划</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading"
              border style="width:100%;" :data="teamWplanList" @selection-change="handleSelectionChange">
      <el-table-column label="订单合同号" align="center" prop="contractCode" />
      <el-table-column label="下单日期" align="center" prop="orderDate" />
      <el-table-column label="产品名称" align="center" prop="bomName" />
      <el-table-column label="规格型号" align="center" prop="bomStandard" />
      <el-table-column label="订单数量" align="center" prop="orderNum" width="80px"/>
      <el-table-column label="已完成数量" align="center" prop="finishNum" width="100px"/>
      <el-table-column label="剩余数量" align="center" prop="nextNum" width="80px">
      </el-table-column>
      <el-table-column label="标签文档" align="center" class-name="small-padding fixed-width" prop="blabelCheck" width="80px">
      <template slot-scope="scope">
          <el-checkbox v-model="scope.row.blabelCheck"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="包装单" align="center" class-name="small-padding fixed-width" prop="bpackageCheck" width="60px">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.bpackageCheck"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="排产数量" align="center" prop="planCapacity"  width="80px"/>
      <el-table-column label="计划开始日期" align="center" prop="wplanStartDate"  width="100px"/>
      <el-table-column label="计划完成日期" align="center" prop="wplanEndDate"  width="100px" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wplanEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="60px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdjust(scope.row)"
            v-hasPermi="['factory:factorywplan:edit']"
          >调整</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

      <!-- 排产调整对话框 -->
      <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
       <div style="margin-bottom: 20px;text-align: center;">
         <el-row :gutter="16">
           <el-col :span="4" style="margin-right: 100px;">
             <div>
               计划开始日期：
               <el-date-picker
                 clearable
                 v-model="adjustWplanSelected.wplanStartDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="计划开始日期"
                 @change="wplanDateChange"
               >
               </el-date-picker>
             </div>
           </el-col>
           <el-col :span="4">
             <div>
               计划结束日期：
               <el-date-picker
                 clearable
                 v-model="adjustWplanSelected.wplanEndDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="计划结束日期"
                 @change="wplanDateChange"
               >
               </el-date-picker>
             </div>
           </el-col>
         </el-row>
       </div>
      <el-table v-loading="loading" :data="adjustWplanSelected.wplanDetailList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="排产日期" align="center" prop="planDate" width="300">
          <template slot-scope="scope">
            <el-date-picker
              clearable
              v-model="scope.row.planDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="排产数量" align="center" prop="planCapacity" width="200px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.planCapacity" placeholder="排产数量" clearable ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.$index>0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="wplanDateRemove(scope.row)"
              v-hasPermi="['factory:factorywplan:edit']"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排产调整对话框
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="500px"
      append-to-body
    >
      <el-form ref="form2" :model="form2" :rules="rules" label-width="120px">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="wplanStartDate">
              <el-date-picker
                clearable
                v-model="form2.wplanStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="完成时间" prop="wplanEndDate">
              <el-date-picker
                clearable
                v-model="form2.wplanEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择完成时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import { printFactorywplan, listFactoryPrintwplan,printPlan,adjustWplan,getWeekOfMonth } from "@/api/sm/factory/factorywplan";
import { listTeam } from "@/api/system/dept";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      teamSelect: true,
      planCal: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      //分厂待排产订单信息表格数据
      teamWplanList: [],
      adjustWplanSelected: {},
      teamList: [],
      monthList: [
        {
          "label": "2024年1月",
          "value": '202401'
        },
        {
          "label": "2024年2月",
          "value": '202402'
        },
        {
          "label": "2024年3月",
          "value": '202403'
        },
        {
          "label": "2024年4月",
          "value": '202404'
        },
        {
          "label": "2024年5月",
          "value": '202405'
        },
        {
          "label": "2024年6月",
          "value": '202406'
        },
        {
          "label": "2024年7月",
          "value": '202407'
        },
        {
          "label": "2024年8月",
          "value": '202408'
        },
        {
          "label": "2024年9月",
          "value": '202409'
        },
        {
          "label": "2024年10月",
          "value": '202410'
        },
        {
          "label": "2024年11月",
          "value": '202411'
        },
        {
          "label": "2024年12月",
          "value": '202412'
        }
      ],
      weekList: [
        {
          "label": "第1周",
          "value": '-1'
        },
        {
          "label": "第2周",
          "value": '-2'
        },
        {
          "label": "第3周",
          "value": '-3'
        },
        {
          "label": "第4周",
          "value": '-4'
        },
        {
          "label": "第5周",
          "value": '-5'
        }
      ],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        },
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adjustopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamId: null,
        month: null,
        week: null,
        monthWeek: null,
        teamIds: [],
      },
      // 表单参数
      form: {
        planMonth: null,
        workOrderIds: null
      },
      form2: {
        id: null,
        wplanStartDate: null,
        wplanEndDate: null
      },
      // 表单参数
      form1: {
        wplanList: null
      },
      // 表单校验
      rules: {
      },
    };
  },
  created() {
    this.queryParams.month = this.getCurrentDate();
    this.getWeekOfMonth();
    this.getTeamList();
    this.getList();
  },
  methods: {

    getFirstMondayOfMonth(date) {
      // 将日期设置为当月的第一天
      date.setDate(1);

      // 获取当月第一天是周几
      let dayOfWeek = date.getDay();

      // 如果当月的第一天就是周一，那么就是当月的第一个周一
      if (dayOfWeek === 1) {
        return date;
      }

      // 如果当月的第一天不是周一，那么就往前数(7 - dayOfWeek + 1)天
      date.setDate(date.getDate() + (7-dayOfWeek + 1));
      return date;
    },
    getWeekOfMonth(){
      let date = new Date(); // 当前日期
      let firstMonday = this.getFirstMondayOfMonth(date);
      let days = this.selectDay((Date.parse(firstMonday))/1000);
      var weeks =Math.ceil(14/7);
      this.queryParams.week="-"+weeks;

    },
    selectDay(starttime){
      var today=(Date.parse(new Date()))/1000;//当前时间戳
      var nTime = today - starttime;
      var day =Math.floor(nTime/86400);
      return day;
    },

    formatDateToYYYYMMDD(date) {
      const year = date.getFullYear();
      let month = date.getMonth() + 1; // 月份是从 0 开始的，需要加 1
      let day = date.getDate();

      // 如果月份或日期小于 10，前面补零
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day;
      }
      return `${year}-${month}-${day}`;
    },
    wplanDateRemove(row) {
      let wplanList = this.adjustWplanSelected.wplanDetailList;
      if (wplanList.length === 0) {
        alert('已经无日期删除');
      }
      for(let i=0;i<wplanList.length;i++) {
        let obj = wplanList[i];
        if (obj.planDate === row.planDate) {
          wplanList.splice(i, 1);
          break;
        }
      }
    },
    wplanDateChange() {
      let wplanDetailList = this.adjustWplanSelected.wplanDetailList;
      if (wplanDetailList.length === 0) {
        alert('已经无日期调整');
      }
      let cloneSrcObject = this.adjustWplanSelected.wplanDetailList[0];
      const start = new Date(this.adjustWplanSelected.wplanStartDate);
      const end = new Date(this.adjustWplanSelected.wplanEndDate);
      // 循环变量从起始日期开始，逐天增加
      let currentDate = new Date(start);
      while (currentDate <= end) {
        let curPlanDate = this.formatDateToYYYYMMDD(currentDate);
        const exists = this.adjustWplanSelected.wplanDetailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.wplanDetailList.push(rowWPlan);
        }
        // 增加一天
        currentDate.setDate(currentDate.getDate() + 1);
      }
    },
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1; // 月份是从0开始的，所以需要加1
      return `${year}${month.toString().padStart(2, '0')}`;
    },
     /** 调整排产日期功能 提交按钮 */
    submitAdjustForm() {
      if(this.adjustWplanSelected.wplanEndDate<this.adjustWplanSelected.wplanStartDate){
        alert("完成时间不能小于开始时间");
        return;
      }
      adjustWplan(this.adjustWplanSelected).then(response => {
        this.$modal.msgSuccess("周排产调整成功");
        this.adjustopen = false;
        this.getList();
      });
    },
    cancel2() {
      this.adjustopen = false;
      this.reset2();
    },
    reset2(){
      this.form2 = {
        id: null,
        wplanStartDate: null,
        wplanEndDate: null
      };
      this.resetForm("form2");
    },
    handleAdjust(row) {
      this.reset2();
      this.adjustopen = true;
      this.adjustWplanSelected = row;
      // this.form2.id = row.id;
      // this.form2.wplanStartDate = row.wplanStartDate;
      // this.form2.wplanEndDate = row.wplanEndDate;
    },

    //打印周计划
    printPlan() {
      printFactorywplan(this.queryParams).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '周排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    /** 查询订单信息列表 */
    getTeamList() {
      this.loading = true;
      listTeam().then(response => {
        this.teamList = response.data;
        if (this.teamList) {
          this.queryParams.teamIds = this.teamList.map(item => item.deptId);
        }
        this.loading = false;
      });
    },

    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printWplanWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '月排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.monthWeek=this.queryParams.month+this.queryParams.week;
      listFactoryPrintwplan(this.queryParams).then(response => {
        this.teamWplanList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // if(this.queryParams.teamId==null || this.queryParams.teamId==undefined){
      //   alert("请先选择班组,打印月份，周数后才能查询");
      //   return;
      // }
      if(this.queryParams.month==null || this.queryParams.month==undefined){
        alert("请先选择班组,打印月份，周数后才能查询");
        return;
      }
      if(this.queryParams.week==null || this.queryParams.week==undefined){
        alert("请先选择班组,打印月份，周数后才能查询");
        return;
      }
      this.teamSelect = false;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
  }
};
</script>
